﻿using CustomCharacter;
using CustomPlayerEffects;
using Exiled.API.Enums;
using Exiled.API.Extensions;
using Exiled.API.Features;
using Exiled.API.Features.Roles;
using Exiled.Events.EventArgs.Interfaces;
using Exiled.Events.EventArgs.Player;
using MEC;
using PlayerStatsSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Player = Exiled.API.Features.Player;
using CustomCharacter.Ability;
using CustomCharacter.Interfaces;
using RgCore.Events;
using RgCore.API;
using RgCore.CustomSide;
using RgCore.Misc;
using RgCore.PlayerHud;

namespace Scp999
{
    [RoleInfo("SCP-999", Side.None, PlayerRoles.RoleTypeId.ClassD, PlayerRoles.RoleTypeId.Tutorial,
        MaxHealth = 300)]
    public class Scp999 : CustomCharacter.CustomCharacter, IScpNumber, ICustomSpawnpoint, IRoundStartSpawn, ITrialCard
    {
        public Scp999(int id) : base(id)
        {
        }

        public int Cost => 400;
        public Vector3 SpawnPosition => Room.List.Where(x => x.Type == RoomType.EzTCross).First().Position + Vector3.up * 1.5f;
        public override Color32 RoleColor => new Color32(34, 139, 34, 255);

        public string ScpNumber => "999";

        public byte MinPlayers => 10;

        private static AbilityOutput Ability1(Player p, ref AbilityInfo info, IExiledEvent e, AbilityTrigger trigger)
        {
            if (trigger == AbilityTrigger.Active_Update)
            {
                foreach (Player player in Player.List.Where(x => p.GetSide() == Side.None || p.IsFriendly(x)))
                {
                    float dis = Vector3.Distance(player.Position, p.Position);
                    if (dis <= 10f)
                    {
                        if (player.IsScp)
                        {
                            player.Heal(player.MaxHealth * 0.01f);
                        }
                        else
                        {
                            player.Heal(5f);
                        }
                    }
                }
                return new AbilityOutput(true, false, 0, "");
            }
            if (info.CooldownStatus.Status.HasFlag(CooldownStatus<Player>.CdStatus.Activating))
            {
                return new AbilityOutput(false, "技能正在激活中");
            }
            info.CooldownStatus.StartCD();
            return new AbilityOutput(true, true, 15, "开始治疗自己及附近玩家，持续15秒");
        }

        public static AbilityOutput Ability2(Player p, ref AbilityInfo info, IExiledEvent e, AbilityTrigger trigger)
        {
            var ab = p.GetAbility("Scp999_Attr_1");
            if (ab.Ability == null)
                return new AbilityOutput(false, "此技能需要SCP-999的特性技能才能正常使用");
            var data = ab.Datas;
            Player player = null;
            float range = 10f;
            foreach (Player ply in Player.List)
            {
                float playerRange = Vector3.Distance(p.Position, ply.Position);
                if (ply == p || ply.GetSide() == Side.Scp || ply.MaxHealth > 150f || playerRange > range)
                {
                    continue;
                }

                range = playerRange;
                player = ply;
            }
            if (player is null)
            {
                return new AbilityOutput(false, "附近没有可以祝福的对象");
            }
            player.SendRawMsg("", "[<color=green>SCP-999</color>] 得到祝福，在90秒内濒死会重生在此处", 5, ScreenLocation.CenterBottom, true);
            data["blessee"] = player;
            data["position_x"] = player.Position.x;
            data["position_y"] = player.Position.y;
            data["position_z"] = player.Position.z;
            data["blesstime"] = DateTime.Now.ToString();
            return new AbilityOutput(true, $"你祝福了 <color=yellow>{player.Nickname}</color>");
        }

        private static AbilityOutput Ability3(Player p, ref AbilityInfo info, IExiledEvent e, AbilityTrigger trigger)
        {
            int pl = 0;
            foreach (Player player in Player.List.Where(x => p.GetSide() == Side.None ? x.GetSide() != Side.Scp : p.IsFriendly(x)))
            {
                float dis = Vector3.Distance(player.Position, p.Position);
                if (dis <= 10f)
                {
                    pl++;
                    player.ReferenceHub.playerStats.GetModule<StaminaStat>().ModifyAmount(1f);
                    player.ReferenceHub.playerStats.GetModule<AhpStat>().ServerAddProcess(40f);
                    player.ReferenceHub.playerEffectsController.EnableEffect<Invigorated>(8f, true);
                    player.ReferenceHub.playerEffectsController.DisableEffect<AmnesiaVision>();
                    foreach (StatusEffectBase statusEffectBase in player.ReferenceHub.playerEffectsController.AllEffects)
                    {
                        if (statusEffectBase is IHealablePlayerEffect healablePlayerEffect && healablePlayerEffect.IsHealable(ItemType.Adrenaline))
                        {
                            statusEffectBase.IsEnabled = false;
                        }
                    }
                    player.SendRawMsg("", "[<color=green>强化</color>] 已释放肾上腺素，你被强化了，快上！", 3, ScreenLocation.CenterBottom, true);
                }
            }
            p.AddScore(pl * 10, "强化队友");
            return new AbilityOutput(true, "已释放肾上腺素效果！");
        }

        private static AbilityOutput Attribute_1(Player p, ref AbilityInfo info, IExiledEvent e, AbilityTrigger trigger)
        {
            var blessee = info.Datas["blessee"];
            if (e == null)
            {
                DateTime BlessTime = DateTime.Parse(info.Datas["blesstime"].ToString());
                if (blessee != null)
                {
                    Player Blessee = (Player)blessee;
                    if (BlessTime.AddSeconds(90) > DateTime.Now)
                    {
                        if (!Blessee.HasMsg("bless"))
                        {
                            Blessee.SendRawMsg("bless", API.GetGradientString("⚜SCP-999の祝福生效中⚜", new Color32(6, 180, 139, 255), new Color32(204, 0, 85, 255)), 0, ScreenLocation.Top, false);
                        }
                    }
                    else
                    {
                        if (Blessee.HasMsg("bless"))
                            Blessee.DeleteMsg("bless", false);
                        info.Datas["blessee"] = null;
                    }
                }
                p.Heal(2f);
                return false;
            }
            if (e is HurtingEventArgs ev1 && ev1.Player == p && ev1.DamageHandler.Base is AttackerDamageHandler)
            {
                if (ev1.DamageHandler.Base is ScpDamageHandler)
                {
                    ev1.Amount = 10f;
                }
                else if (ev1.DamageHandler.Base is FirearmDamageHandler)
                {
                    ev1.Amount *= 0.3f;
                }
                return false;
            }
            if (e is SearchingPickupEventArgs ev2 && ev2.Player == p && ev2.Pickup.Type.GetCategory() != ItemCategory.Medical && ev2.Pickup.Type != ItemType.SCP500)
            {
                p.SendRawMsg("denied", $"由于技能限制，只能拾起医疗物品和SCP-500", 2, ScreenLocation.CenterBottom, true);
                ev2.IsAllowed = false;
                return false;
            }
            if (e is InteractingDoorEventArgs ev3 && ev3.Player == p && ev3.Door.IsCheckpoint)
            {
                ev3.IsAllowed = true;
                return false;
            }
            if (e is EnteringPocketDimensionEventArgs ev4 && ev4.Player == p)
            {
                ev4.IsAllowed = false;
                return false;
            }
            if (e is UsingItemEventArgs ev5 && ev5.Player == p && ev5.Item.Type != ItemType.SCP500)
            {
                p.SendRawMsg("denied", $"由于技能限制，只能使用SCP-500", 2, ScreenLocation.CenterBottom, true);
                ev5.IsAllowed = false;
                return false;
            }
            if (e is DyingEventArgs ev6 && ev6.Player == blessee)
            {
                info.Datas["blessee"] = null;
                ev6.Player.DeleteMsg("bless", false);
                if (ev6.DamageHandler.Base is WarheadDamageHandler || (ev6.DamageHandler.Base is UniversalDamageHandler && ev6.Player.TryGetEffect(EffectType.Decontaminating,out _)))
                {
                    ev6.Player.SendFormattedMsg("", $"", "祝福失效！肉体湮灭！", 5, MsgType.Notification, ScreenLocation.CenterTop, true);
                    p.AddScore(100,"祝福湮灭");
                    return new AbilityOutput(false);
                }
                ev6.IsAllowed = false;
                ev6.Player.Health = ev6.Player.MaxHealth * 0.1f;
                ev6.Player.DisableAllEffects();
                ev6.Player.IsGodModeEnabled = true;
                Timing.CallDelayed(3.0f, delegate ()
                {
                    ev6.Player.IsGodModeEnabled = false;
                });
                ev6.Player.EnableEffect<Invisible>(3f);
                ev6.Player.Teleport(new Vector3((float)info.Datas["position_x"], (float)info.Datas["position_y"], (float)info.Datas["position_z"]));
                ev6.Player.SendFormattedMsg("", $"", "祝福生效！超越生死！", 5, MsgType.Notification, ScreenLocation.CenterTop, true);
                foreach (Player player in Player.List)
                {
                    if (player.Role is Scp096Role scp096)
                    {
                        scp096.RemoveTarget(ev6.Player);
                    }
                }
                p.AddScore(300, "祝福生效");
            }
            return false;
        }

        public override IEnumerable<Ability> AbilityRegister()
        {
            return new Ability[]
            {
                new Ability("Scp999_1",
                "每秒对自身和附近的任何玩家提供15s治疗", AbilityType.Offensive, 60, Ability1, null, null, null, GetType()),
                new Ability("Scp999_2",
    "给离自己最近的任意最大血量上限在150以下的友方“不死图腾”效果",AbilityType.Offensive, 90, Ability2, null, null, null, GetType()),
                new Ability("Scp999_3",
    "给附近所有的非SCP阵营玩家提供一个肾上腺素效果", AbilityType.Offensive,60, Ability3, null, null, null, GetType()),
                new AttributeAbility("Scp999_Attr_1",
                "只能拾取医疗物品和SCP-500，且只可以使用SCP-500;减伤/自主回血", Attribute_1, true, new IExiledEvent[]
                {
                    EventProcessor.OnHurting,
                    Exiled.Events.Handlers.Player.SearchingPickup,
                    EventProcessor.OnDying,
                    Exiled.Events.Handlers.Player.InteractingDoor,
                    Exiled.Events.Handlers.Player.EnteringPocketDimension,
                    Exiled.Events.Handlers.Player.UsingItem
                }, new KeyValuePair<string, object>[]
    {
        new KeyValuePair<string, object>("blessee", null), new KeyValuePair<string, object>("position_x", 0f),
        new KeyValuePair<string, object>("position_y", 0f), new KeyValuePair<string, object>("position_z", 0f),
        new KeyValuePair<string, object>("blesstime", DateTime.Now.ToString())
    }, GetType())
            };
        }

        public override void Role_Activate()
        {
            base.Role_Activate();
            Player.ClearInventory();
            Player.IsGodModeEnabled = false;
            Timing.CallDelayed(1f, () =>
            {
                Player.Scale = Vector3.one * 0.5f;
            });
        }

        public override void Role_Deactive()
        {
            base.Role_Deactive();
            Player.Scale = Vector3.one;
        }
    }
}